package com.example.weather.DB;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class Dbmanager {
    public static SQLiteDatabase database;
    //初始化数据库
    public static void initdb(Context context){
        Dbhelper dbhelper = new Dbhelper(context);
        database=dbhelper.getWritableDatabase();
    }
    //查找数据库中城市列表
    public static List<String> allcityname(){
        Cursor cursor = database.query("info", null, null, null, null, null,null);
        List<String> citylist=new ArrayList<>();
        while (cursor.moveToNext()) {
            String city = cursor.getString(cursor.getColumnIndex("city"));
            citylist.add(city);
        }
        return citylist;
    }
    //根据城市名称替换信息内容
    public static int updatacity(String city,String content){
        ContentValues values = new ContentValues();
        values.put("content",content);
        return database.update("info",values,"city=?",new String[]{city});
    }
    //第一次获取，添加城市记录
    public static long addcity(String city,String content){
        ContentValues values=new ContentValues();
        values.put("city",city);
        values.put("content",content);
        return database.insert("info",null,values);
    }
    //根据城市名查询数据库中内容
    public static String queryinfo(String city){
        Cursor cursor = database.query("info", null, "city=?", new String[]{city}, null, null, null);
        if (cursor.getCount()>0) {
            cursor.moveToFirst();
            String content = cursor.getString(cursor.getColumnIndex("content"));
            return content;
        }
        return null;
    }
    //存储城市天气要求最多5个，一旦超过5个不能存储，获取目前已经存储的数量
    public static int getcitycount(){
        Cursor cursor = database.query("info", null, null, null, null, null, null);
        int count = cursor.getCount();
        return count;
    }
    //查询数据库中全部信息
    public static List<DataBaseBean> queryall(){
        Cursor cursor = database.query("info", null, null, null, null, null, null);
        List<DataBaseBean> list=new ArrayList<>();
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String city = cursor.getString(cursor.getColumnIndex("city"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            DataBaseBean bean = new DataBaseBean(id, city, content);
            list.add(bean);
        }
        return list;
    }
    //根据城市名称删除城市数据
    public static int deletecity(String city){
        return database.delete("info","city=?",new String[]{city});
    }
    //删除表中所有数据消息
    public static void deleteall(){
        String sql="delete from info";
        database.execSQL(sql);
    }
}
